<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\UploadedFile;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\SensorVersion;
use common\models\ProFile;
use common\models\Group;
use common\models\Config;
use common\models\UserLog;
use common\models\Command;
use common\models\Network;
use yii\helpers\ArrayHelper;
use common\models\Logger;

/**
 * Seting controller
 */
class SetingController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        if (Config::getLicense()['sensorNowCount'] == 0) {
            $rules = [
                [
                    'actions' => ['index', 'license', 'log', 'network', 'get-params', 'set-ip', 'get-set-ip-res', 'get-network', 'set-network'],
                    'allow' => true,
                    'roles' => ['admin'],
                ],
            ];
        } else {
            $rules = [
                ['actions' => [''], 'allow' => true, 'roles' => ['?']],
                ['actions' => [''], 'allow' => true, 'roles' => ['@']],
                ['actions' => [], 'allow' => true, 'roles' => ['admin']]
            ];
        }
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'sensor', 'loophole', 'license', 'group', 'filelist', 'profile', 'user', 'email', 'log', 'network', 'filepage', 'addversion', 'addprofile', 'versionpage', 'profilepage', 'sensordefault', 'profiledefault', 'profiledel', 'sensordel', 'get-params', 'set-ip', 'get-set-ip-res', 'get-network', 'set-network', 'rule', 'get-package-status', 'upload-sdk', 'update-sdk', 'upload-df', 'update-df', 'upload-reg', 'update-reg', 'get-online-update-status', 'get-offline-update-status'],
                'rules' => $rules
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post']
                ]
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null
            ]
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public $enableCsrfValidation = false;

    private function isAPI() {
        $headers = Yii::$app->request->headers;
        if (stristr($headers['accept'], 'application/json') !== false) {
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        } else {
            Yii::$app->response->format = \yii\web\Response::FORMAT_XML;
        }
    }

    public function actionIndex() {
        return $this->render('index');
    }

    public function actionSensor() {
        return $this->render('sensor');
    }

    public function actionLoophole() {
        return $this->render('loophole');
    }

    public function actionLicense() {
        return $this->render('license');
    }

    public function actionGroup() {
        $GroupList = Group::find()->orderBy('level')->all();
        $GroupList = ArrayHelper::toArray($GroupList);
        return $this->render('group', ['GroupList' => $GroupList]);
    }

    public function actionFilelist() {
        return $this->render('filelist');
    }

    public function actionProfile() {
        return $this->render('profile');
    }

    public function actionUser() {
        return $this->render('user');
    }

    public function actionEmail() {
        return $this->render('email');
    }

    public function actionLog() {
        return $this->render('log');
    }

    public function actionNetwork() {
        return $this->render('network');
    }

    public function actionRule() {
        return $this->render('rule');
    }

    public function actionFilepage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }

        $query = FileEX::find()->where(['IsOld' => 0])->orderBy(['id' => SORT_DESC,]);
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $pageData = $query->offSet(($page - 1) * $rows)->limit($rows)->all();
        $data = [
            'data' => ArrayHelper::toArray($pageData),
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'rows' => $rows,
            'status' => 'success',
        ];
        return $data;
    }

    public function actionAddversion() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = Yii::$app->request->post();
        if (empty($post['Version'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Version error';
            return $data;
        }
        $status = isset($post['status']);
        $file_tmp = $_FILES['file'];
        $uid = uniqid();
        $path = Yii::$app->params['staticPath'] . '/sensor/' . $uid . '/';
        mkdir($path, 0777, true);
        move_uploaded_file($file_tmp['tmp_name'], $path . $file_tmp['name']);
        $MD5 = md5_file($path . $file_tmp['name']);
        $version = new SensorVersion();
        $version->Version = $post['Version'];
        $version->Path = '/sensor/' . $uid . '/' . $file_tmp['name'];
        $version->FileName = $file_tmp['name'];
        $version->MD5 = $MD5;
        if ($status) {
            SensorVersion::updateAll(['status' => 0], 'status = 1');
            $version->status = 1;
        }
        $version->save();
        $data = $this->actionVersionpage();
        return $data;
    }

    public function actionAddprofile() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = Yii::$app->request->post();
        if (empty($post['Version'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Version error';
            return $data;
        }
        $status = isset($post['status']);
        $file_tmp = $_FILES['file'];
        $uid = uniqid();
        $path = Yii::$app->params['staticPath'] . '/profile/' . $uid . '/';
        mkdir($path, 0777, true);
        move_uploaded_file($file_tmp['tmp_name'], $path . $file_tmp['name']);
        $profile = new ProFile();
        $profile->Version = $post['Version'];
        $profile->Path = '/profile/' . $uid . '/' . $file_tmp['name'];
        $profile->FileName = $file_tmp['name'];
        if ($status) {
            ProFile::updateAll(['status' => 0], 'status = 1');
            $profile->status = 1;
        }
        $profile->save();
        $data = $this->actionProfilepage();
        return $data;
    }

    public function actionVersionpage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $query = SensorVersion::find()->orderBy(['id' => SORT_DESC]);
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $sensorList = $query->offSet(($page - 1) * $rows)->limit($rows)->asArray()->all();
        $data = [
            'data' => $sensorList,
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'rows' => $rows,
            'status' => 'success',
        ];
        return $data;
    }

    public function actionProfilepage($page = 1, $rows = 15) {
        $this->isAPI();
        if (Yii::$app->request->isPost) {
            $post = json_decode(Yii::$app->request->getRawBody(), true);
            $page = empty($post['page']) ? $page : $post['page'];
            $rows = empty($post['rows']) ? $rows : $post['rows'];
        }
        $query = ProFile::find()->orderBy(['id' => SORT_DESC]);
        $page = (int) $page;
        $rows = (int) $rows;
        $count = (int) $query->count();
        $maxPage = ceil($count / $rows);
        $page = $page > $maxPage ? $maxPage : $page;
        $sensorList = $query->offSet(($page - 1) * $rows)->limit($rows)->asArray()->all();
        $data = [
            'data' => $sensorList,
            'count' => $count,
            'maxPage' => $maxPage,
            'pageNow' => $page,
            'rows' => $rows,
            'status' => 'success',
        ];
        return $data;
    }

    public function actionSensordefault() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        if (empty($post['id'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'ID error';
            return $data;
        }
        $id = $post['id'];
        $page = empty($post['page']) ? 1 : (int) $post['page'];
        $version = SensorVersion::findOne($id);
        if (empty($version)) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'This SensorVersion does not exist';
            return $data;
        }
        SensorVersion::updateAll(['status' => 0], 'status = 1');
        $version->status = 1;
        $version->save();
        $data = $this->actionVersionpage($page);
        return $data;
    }

    public function actionProfiledefault() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        if (empty($post['id'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'ID error';
            return $data;
        }
        $id = $post['id'];
        $page = empty($post['page']) ? 1 : (int) $post['page'];
        $version = ProFile::findOne($id);
        if (empty($version)) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'This ProFile does not exist';
            return $data;
        }
        ProFile::updateAll(['status' => 0], 'status = 1');
        $version->status = 1;
        $version->save();
        $data = $this->actionProfilepage($page);
        return $data;
    }

    public function actionProfiledel() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        if (empty($post['id'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'ID error';
            return $data;
        }
        $id = $post['id'];
        $page = empty($post['page']) ? 1 : (int) $post['page'];
        $version = ProFile::findOne($id);
        if (empty($version)) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'This ProFile does not exist';
            return $data;
        }
        $version->delete();
        $data = $this->actionProfilepage($page);
        return $data;
    }

    public function actionSensordel() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        if (empty($post['id'])) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'ID error';
            return $data;
        }
        $id = $post['id'];
        $page = empty($post['page']) ? 1 : (int) $post['page'];
        $version = SensorVersion::findOne($id);
        if (empty($version)) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'This SensorVersion does not exist';
            return $data;
        }
        $version->delete();
        $data = $this->actionVersionpage($page);
        return $data;
    }

    public function actionGetParams() {
        $this->isAPI();
        $data = [
            'status' => 'success',
            'params' => Yii::$app->params,
        ];
        return $data;
    }

    public function actionGetSetIpRes($CommandID) {
        $this->isAPI();
        $command = Command::find()->where(['CommandID' => $CommandID])->one();
        if (empty($command)) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Without this command.';
            return $data;
        }
        $data = [
            'status' => 'success',
            'data' => $command->data,
            'CommandStatus' => $command->status,
        ];
        return $data;
    }

    public function actionSetIp() {
        $this->isAPI();
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        $command = new Command;
        $command_data['shell'] = Yii::$app->params['confPath'] . '/setIP.sh ' . $post['selfIP'] . ' ' . $post['engineIP'];
        $command->data = $command_data;
        $command->Type = Command::MSG_SHELL_SETIP;
        $command->status = Command::STATUS_UNSENT;
        $command->save();
        $userLog = new UserLog();
        $userLog->type = UserLog::Type_EngineDown;
        $userLog->status = UserLog::Success;
        $userLog->info = 'The engine has stopped';
        $userLog->save();
        $data = [
            'status' => 'success',
            'CommandID' => $command->CommandID,
        ];
        return $data;
    }

    public function actionGetNetwork() {
        $this->isAPI();
        return [
            'status' => 'success',
            'data' => Network::getNetWork()
        ];
    }

    public function actionSetNetwork() {
        $this->isAPI();
        if (!Yii::$app->request->isPost) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
        $command = Network::setNetWork($post);
        $data = [
            'status' => 'success',
            'CommandID' => $command->CommandID,
        ];
        return $data;
    }

    //获取proxy
    public function actionGetProxy() {
        $this->isAPI();
        $data = ['status' => 'success'];
        if (!Yii::$app->request->isGet) {
            $data['status'] = 'fail';
            $data['errorMessage'] = 'Not get request';
            return $data;
        }
        $file_path = '/opt/proxy_config/proxy';
        if (!file_exists($file_path)) {
            $data['data'] = ['http' => '', 'https' => ''];
            return $data;
        }
        $file_arr = file($file_path);
        $data['data'] = ['http' => trim($file_arr[0]) == 'xxxxxxxxxx' ? '' : trim($file_arr[0]), 'https' => trim($file_arr[1]) == 'xxxxxxxxxx' ? '' : trim($file_arr[1])];
        return $data;
    }

    //配置proxy
    public function actionSetProxy() {
        $this->isAPI();
        $data['status'] = 'fail';
        if (!Yii::$app->request->isPut) {
            $data['errorMessage'] = 'Not post request';
            return $data;
        }
        $post = json_decode(Yii::$app->request->getRawBody(), true);
//        p($post);die;
        //参数验证
        if (count($post) != 2 || !array_key_exists('http', $post) || !array_key_exists('http', $post)) {
            $data['errorMessage'] = '参数错误';
            return $data;
        }
        if ((!preg_match('/^(http|https|socks5):\/\/((\w){1,64}:(\w){1,64}@){0,1}((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){3}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9]))(:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])){0,1}$/', $post['http']) && $post['http']) || (!preg_match('/^(http|https|socks5):\/\/((\w){1,64}:(\w){1,64}@){0,1}((1[0-9][0-9]\.)|(2[0-4][0-9]\.)|(25[0-5]\.)|([1-9][0-9]\.)|([0-9]\.)){3}((1[0-9][0-9])|(2[0-4][0-9])|(25[0-5])|([1-9][0-9])|([0-9]))(:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])){0,1}$/', $post['https']) && $post['https'])) {
            $data['errorMessage'] = '代理服务器格式错误';
            return $data;
        }
        //生成上传目录
        $upload_dir = '/opt/proxy_config/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        $myfile = fopen($upload_dir . '/proxy', "w");
        $txt = $post['http'] ? $post['http'] : 'xxxxxxxxxx';
        fwrite($myfile, $txt);
        fwrite($myfile, "\r\n");
        $txt = $post['https'] ? $post['https'] : 'xxxxxxxxxx' . "\r\n";
        fwrite($myfile, $txt);
        fwrite($myfile, "\r\n");
        fclose($myfile);
        return ['status' => 'success'];
    }

    //获取更新包状态
    public function actionGetPackageStatus() {
        $this->isAPI();
        //生成上传目录
        $upload_dir = '/opt/update_package/';
        $sdk_exist = file_exists($upload_dir . 'sdk/sdk.tar.gz');
        $df_exist = file_exists($upload_dir . 'df/df.tar.gz');
        $reg_exist = file_exists($upload_dir . 'reg/reg.tar.gz');
        return [
            'status' => 'success',
            'data' => [
                'sdk_exist' => $sdk_exist ? $sdk_exist : false,
                'df_exist' => $df_exist ? $df_exist : false,
                'reg_exist' => $reg_exist ? $reg_exist : false
            ]
        ];
    }

    //获取实时更新状态
    public function actionGetOnlineUpdateStatus() {
        $this->isAPI();
        $VirOnlineUpdateStatus = Yii::$app->redis->hgetall('VirOnlineUpdateStatus');
        $RegOnlineUpdateStatus = Yii::$app->redis->hgetall('RegOnlineUpdateStatus');
        return ['status' => 'success', 'data' => ['VirOnlineUpdateStatus' => $VirOnlineUpdateStatus, 'RegOnlineUpdateStatus' => $RegOnlineUpdateStatus]];
    }

    //获取离线更新状态
    public function actionGetOfflineUpdateStatus() {
        $this->isAPI();
        $VirOfflineUpdateStatus = Yii::$app->redis->hgetall('VirOfflineUpdateStatus');
        $RegOfflineUpdateStatus = Yii::$app->redis->hgetall('RegOfflineUpdateStatus');
        $DfOfflineUpdateStatus = Yii::$app->redis->hgetall('DfOfflineUpdateStatus');
        return ['status' => 'success', 'data' => ['VirOfflineUpdateStatus' => $VirOfflineUpdateStatus, 'RegOfflineUpdateStatus' => $RegOfflineUpdateStatus, 'DfOfflineUpdateStatus' => $DfOfflineUpdateStatus]];
    }

    //实时更新
    public function actionRealtimeUpdate() {
        $this->isAPI();
        $VirOnlineUpdateStatus = Yii::$app->redis->hgetall('VirOnlineUpdateStatus');
        exec('/usr/bin/python /opt/icatch_engine/script/update_vir_online_web.py' . ' > /dev/null &');
        $RegOnlineUpdateStatus = Yii::$app->redis->hgetall('RegOnlineUpdateStatus');
        exec('/usr/bin/python /opt/icatch_engine/script/update_reg_online_web.py' . ' > /dev/null &');
        return ['status' => 'success'];
    }

    //上传更新包
    public function actionUploadPackage() {
        \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        header("Access-Control-Allow-origin:*");
        header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");
        $return = ['status' => 'fail'];
        // Support CORS
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if (!empty($_REQUEST['debug'])) {
            $random = rand(0, intval($_REQUEST['debug']));
            if ($random === 0) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        $fileName = $_FILES['file']["name"];
        //当上传错误时
        if (empty($fileName)) {
            $return['errorMessage'] = '请选择要上传的文件，重新上传';
            return $return;
        }
        //判别是不合法的文件
        if (!in_array($fileName, ['sdk.tar.gz', 'df.tar.gz', 'reg.tar.gz'])) {
            $return['errorMessage'] = '请上传名为sdk.tar.gz、df.tar.gz或reg.tar.gz的文件';
            return $return;
        }
        // header("HTTP/1.0 500 Internal Server Error");
        // 5 minutes execution time
        @set_time_limit(5 * 60);
        $targetDir = '/opt/update_package/';
        $uploadDir = '/opt/update_package/' . explode(".", $fileName)[0] . '/';
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
        // Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir);
        }
        $filePath = $targetDir . $fileName;
        $uploadPath = $uploadDir . explode(".", $fileName)[0] . '.tar.gz';
        $random = $_COOKIE['advanced-frontend'];
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                $return['errorMessage'] = '上传文件失败';
                return $return;
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . $file;
                if ($tmpfilePath == "{$filePath}_{$random}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$random}_{$chunk}.parttmp") {
                    continue;
                }
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = @fopen("{$filePath}_{$random}_{$chunk}.parttmp", "wb")) {
            $return['errorMessage'] = '上传文件失败';
            return $return;
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                $return['errorMessage'] = '上传文件失败';
                return $return;
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                $return['errorMessage'] = '上传文件失败';
                return $return;
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                $return['errorMessage'] = '上传文件失败';
                return $return;
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$random}_{$chunk}.parttmp", "{$filePath}_{$random}_{$chunk}.part");
        $index = 0;
        $done = true;
        for ($index = 0; $index < $chunks; $index++) {
            if (!file_exists("{$filePath}_{$random}_{$index}.part")) {
                $done = false;
                break;
            }
        }
        if ($done) {
            if (!$out = @fopen($uploadPath, "wb")) {
                $return['errorMessage'] = '上传文件失败';
                return $return;
            }
            if (flock($out, LOCK_EX)) {
                for ($index = 0; $index < $chunks; $index++) {
                    if (!$in = @fopen("{$filePath}_{$random}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    @fclose($in);
                    @unlink("{$filePath}_{$random}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            @fclose($out);
        }
        return ['status' => 'success'];
    }

    //离线更新
    public function actionOfflineUpdating() {
        $this->isAPI();
        $return = ['status' => 'fail'];
        if (!Yii::$app->request->isPost) {
            $return['errorMessage'] = '请求失败';
            return $return;
        }
        //判断是否存在升级吧
        $update_file = '/opt/update_package/';
        $exist_count = 0;
        if (file_exists($update_file . 'sdk/sdk.tar.gz')) {
            $exist_count += 1;
            exec('/usr/bin/python /opt/icatch_engine/script/update_vir_offline.py' . ' > /dev/null &');
        }
        if (file_exists($update_file . 'df/df.tar.gz')) {
            $exist_count += 1;
            exec('/usr/bin/python /opt/icatch_engine/script/update_df_offline.py' . ' > /dev/null &');
        }
        if (file_exists($update_file . 'reg/reg.tar.gz')) {
            exec('/usr/bin/python /opt/icatch_engine/script/update_reg_offline.py' . ' > /dev/null &');
            $exist_count += 1;
        }
        if ($exist_count == 0) {
            $return['errorMessage'] = '请先上传更新包再执行更新操作';
            return $return;
        }
        return ['status' => 'success'];
    }

}
